import * as Remote from '../services'
const TabsModel = {
    namespace: 'tabs',
    state: {
        pages: [],
        activeWindowId : 0
    },
    effects: {
        *getPages({ payload }, { call, put }) {
            let ret = yield call(Remote.getPages,payload);
            yield put({
                type:'init',
                payload:{
                    pages:ret.pages,
                    activeWindowId :ret.activeWindowId
                }
            })
        },
        *newPage({ payload }, { call, put }) {
            let ret = yield call(Remote.newPage,payload);
            yield put({
                type:'getPages',
                payload:{}
            });
            yield put({
                type:'addressBar/init',
                payload:{url:''}
            })
        },
        *changePage({ payload }, { call, put }) {
            let ret = yield call(Remote.changePage,payload);
            yield put({
                type:'getPages',
                payload:{}
            })
        },
        *closePage({ payload }, { call, put }) {
            let ret = yield call(Remote.closePage,payload);
            yield put({
                type:'getPages',
                payload:{}
            })
        },
    },
    reducers: {
        init(state, action) {
            return {
                ...state,
                ...action.payload,
            };
        },
        updateTab(state,{payload}){
            console.log('收到了 updateTab',payload);
            let pages = state.pages.map((page)=>{
                if(page.windowId === payload.windowId){
                    page.title = payload.title;
                    page.url = payload.url;
                }
                return page;
            });
            console.log(pages);
            return {
                ...state,
                pages
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                if (pathname === '/') {
                    dispatch({
                        type: 'getPages',
                    })
                }
            });
        }
    }
};

export default TabsModel;